//
//  PaperOptionView.m
//  JW_BasePorject
//
//  Created by JW on 2018/6/27.
//  Copyright © 2018年 JW. All rights reserved.
//

#import "PaperOptionView.h"

#import <DTCoreText/DTCoreText.h>
#import <DTFoundation/DTAnimatedGIF.h>


NSString *html = @"<html><body>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cildo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum  Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</body></html>";

@interface PaperOptionView ()<DTAttributedTextContentViewDelegate,DTLazyImageViewDelegate>

@property (nonatomic, strong)UILabel *optionLabel;

@property (nonatomic, strong)DTAttributedLabel *contentLabel;

@property (nonatomic, assign) CGRect viewMaxRect;


@end

@implementation PaperOptionView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
//    NSLog(@"layoutSubviews: %@", NSStringFromCGSize(self.frame.size));
    [self handleDTLabelDisplay];

}


- (void)setIsSingle:(BOOL)isSingle{
    _isSingle = isSingle;
    
}

- (void)setSelected:(BOOL)selected{
    if (selected) {
        self.backgroundColor = [UIColor greenColor];
    }else{
        self.backgroundColor = [UIColor yellowColor];
    }
    
}




#pragma mark - 添加子控件
- (void)addChildViews{
    
    self.optionLabel.text = @"A";
    self.optionLabel.backgroundColor = ZhuTiColor;
    self.optionLabel.frame = CGRectMake(5, 5, 30, 30);
    ViewBorderRadius(self.optionLabel, 15, 1, [UIColor lightGrayColor]);
    [self.contentView addSubview:self.optionLabel];
    
    [self.contentView addSubview:self.contentLabel];
    
//    [self handleDTLabelDisplay];

}

- (void)handleDTLabelDisplay{
    NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithHTMLData:data documentAttributes:NULL];
    self.contentLabel.attributedString = attributedString;
    
    DTCoreTextLayouter *layouter = [[DTCoreTextLayouter alloc] initWithAttributedString:attributedString];
    NSLog(@"handleDTLabelDisplay: %@", NSStringFromCGSize(self.frame.size));

    CGRect maxRect = CGRectMake(40, 5, self.frame.size.width - 40, CGFLOAT_HEIGHT_UNKNOWN);
    _viewMaxRect = maxRect;
    NSRange entireString = NSMakeRange(0, [attributedString length]);
    DTCoreTextLayoutFrame *layoutFrame = [layouter layoutFrameWithRect:maxRect range:entireString];
    
    CGSize sizeNeeded = [layoutFrame frame].size;
    
    
    self.contentLabel.frame = CGRectMake(40, 5, self.frame.size.width - 40, sizeNeeded.height);
    
    [self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, sizeNeeded.height+10)];
}


+ (PaperOptionView *)cellWithTableView:(UITableView *)tableView{
    static NSString *ident = @"cellSmall";
    
    PaperOptionView *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (!cell) {
        cell = [[PaperOptionView alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self addChildViews];
    }
    return  self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

}




#pragma mark - DTAttributedTextContentViewDelegate

- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame{
    
    if ([attachment isKindOfClass:[DTImageTextAttachment class]]) {
        NSString *imageURL = [NSString stringWithFormat:@"%@", attachment.contentURL];
        DTLazyImageView *imageView = [[DTLazyImageView alloc] initWithFrame:frame];
        imageView.delegate = self;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = [(DTImageTextAttachment *)attachment image];
        imageView.url = attachment.contentURL;
        
        if ([imageURL containsString:@"gif"]) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData *gifData = [NSData dataWithContentsOfURL:attachment.contentURL];
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image = DTAnimatedGIFFromData(gifData);
                });
            });
        }
        
        return imageView;

    }
    
    return nil;
}


#pragma mark - DTLazyImageViewDelegate
//懒加载获取图片大小
- (void)lazyImageView:(DTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size {
    NSURL *url = lazyImageView.url;
    CGSize imageSize = size;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
    BOOL didUpdate = NO;
    // update all attachments that match this URL (possibly multiple images with same size)
    for (DTTextAttachment *oneAttachment in [self.contentLabel.layoutFrame textAttachmentsWithPredicate:pred])
    {
        // update attachments that have no original size, that also sets the display size
        if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero))
        {
            oneAttachment.originalSize = imageSize;
            [self configNoSizeImageView:url.absoluteString size:imageSize];
            didUpdate = YES;
        }
    }
    
}

- (void)configNoSizeImageView:(NSString *)url size:(CGSize)size
{
    CGFloat imgSizeScale = size.height/size.width;
    //    CGFloat widthPx = _viewMaxRect.size.width;
    //    CGFloat heightPx = widthPx * imgSizeScale;
    CGFloat widthPx = size.width;
    CGFloat heightPx = widthPx * imgSizeScale;
    
    NSString *imageInfo = [NSString stringWithFormat:@"src=\"%@\"",url];
    NSString *sizeString = [NSString stringWithFormat:@" style=\"width:%.fpx; height:%.fpx;\"",widthPx,heightPx];
    NSString *newImageInfo = [NSString stringWithFormat:@"src=\"%@\"%@",url,sizeString];
    
    if ([html containsString:imageInfo]) {
        NSString *newHtml = [html stringByReplacingOccurrencesOfString:imageInfo withString:newImageInfo];
        // reload newHtml
        
        html = newHtml;
        CGSize textSize = [self getAttributedTextHeightHtml:html with_viewMaxRect:_viewMaxRect];
        self.contentLabel.frame = CGRectMake(_viewMaxRect.origin.x, _viewMaxRect.origin.y, _viewMaxRect.size.width, textSize.height);
        self.contentLabel.attributedString = [self getAttributedStringWithHtml:html];

        [self.contentLabel relayoutText];
    }
}

//使用HtmlString,和最大左右间距，计算视图的高度
- (CGSize)getAttributedTextHeightHtml:(NSString *)htmlString with_viewMaxRect:(CGRect)_viewMaxRect{
    //获取富文本
    NSAttributedString *attributedString =  [self getAttributedStringWithHtml:htmlString];
    //获取布局器
    DTCoreTextLayouter *layouter = [[DTCoreTextLayouter alloc] initWithAttributedString:attributedString];
    NSRange entireString = NSMakeRange(0, [attributedString length]);
    //获取Frame
    DTCoreTextLayoutFrame *layoutFrame = [layouter layoutFrameWithRect:_viewMaxRect range:entireString];
    //得到大小
    CGSize sizeNeeded = [layoutFrame frame].size;
    return sizeNeeded;
}

//Html->富文本NSAttributedString
- (NSAttributedString *)getAttributedStringWithHtml:(NSString *)htmlString{
    //获取富文本
    NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithHTMLData:data documentAttributes:NULL];
    NSMutableAttributedString *s = attributedString.mutableCopy;
    [s addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, attributedString.length)];
    
//    NSString *str = [s htmlString];
    
    return s.copy;
}


#pragma mark - property

- (DTAttributedLabel *)contentLabel{
    if (_contentLabel == nil) {
        _contentLabel = [[DTAttributedLabel alloc] initWithFrame:CGRectZero];
        _contentLabel.delegate = self;
    }
    return _contentLabel;
}

- (UILabel *)optionLabel{
    if (_optionLabel == nil) {
        _optionLabel = [[UILabel alloc] init];
        _optionLabel.textAlignment = NSTextAlignmentCenter;
        _optionLabel.font = [UIFont systemFontOfSize:16];
    }
    return _optionLabel;
}

@end
